<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      :stripe="true"
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="合同类别" prop="contractCategory">
        <el-select
          v-model="queryParams.contractCategory"
          placeholder="请选择合同类别"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.OA_EMPLOYEE_CONTRACT_CATEGORY)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="合同类型" prop="contractType">
        <el-select
          v-model="queryParams.contractType"
          placeholder="请选择合同类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.OA_EMPLOYEE_CONTRACT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="签约员工" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入签约员工"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="合同名称" prop="contractName">
        <el-input
          v-model="queryParams.contractName"
          placeholder="请输入合同名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <!-- <el-form-item label="合同编码" prop="contractCode">
        <el-input
          v-model="queryParams.contractCode"
          placeholder="请输入合同编码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['oa:employee-contracts:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['oa:employee-contracts:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <!-- <el-table-column label="序号" align="center" prop="id" /> -->
      <el-table-column label="姓名" align="center" prop="userName" />
      <el-table-column label="合同名称" align="center" prop="contractName" />
      <el-table-column label="合同类别" align="center" prop="contractCategory">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.OA_EMPLOYEE_CONTRACT_CATEGORY" :value="scope.row.contractCategory" />
        </template>
      </el-table-column>
      <el-table-column label="合同类型" align="center" prop="contractType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.OA_EMPLOYEE_CONTRACT_TYPE" :value="scope.row.contractType" />
        </template>
      </el-table-column>
      <el-table-column label="签约公司" align="center" prop="signingCompany" />
      <el-table-column
        label="签订日期"
        align="center"
        prop="signingDate"
        :formatter="dateFormatter2"
        width="110px"
      />
      <el-table-column
        label="合同开始时间"
        align="center"
        prop="effectiveStartDate"
        :formatter="dateFormatter2"
        width="110px"
      />
      <el-table-column
        label="合同结束时间"
        align="center"
        prop="effectiveEndDate"
        width="110px"
      >
        <template #default="scope">
          {{ scope.row.effectiveEndDate ? formatDate(scope.row.effectiveEndDate, 'YYYY-MM-DD') : '-' }}
        </template>
      </el-table-column>
      <el-table-column
        label="合同到期"
        align="center"
        width="120px"
      >
        <template #default="scope">
          <span :class="getExpiryReminderClass(scope.row.effectiveEndDate)">
            {{ scope.row.effectiveEndDate === null || scope.row.effectiveEndDate === undefined ? '-' : getExpiryDisplayText(scope.row.effectiveEndDate) }}
            <!-- 调试信息: {{ scope.row.effectiveEndDate }} -->
          </span>
        </template>
      </el-table-column>
      <el-table-column label="续签状态" align="center" prop="renewalStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.OA_EMPLOYEE_RENEWAL_STATUS" :value="scope.row.renewalStatus" />
        </template>
      </el-table-column>
      <el-table-column label="变更状态" align="center" prop="modificationStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.OA_EMPLOYEE_MODIFICATION_STATUS" :value="scope.row.modificationStatus" />
        </template>
      </el-table-column>
      <el-table-column label="合同状态" align="center" prop="contractStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.OA_CONTRACT_STATUS" :value="scope.row.contractStatus" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />openView
      <el-table-column label="操作" align="center" min-width="180px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openView('query', scope.row.id)"
            v-hasPermi="['oa:employee-contracts:query']"
          >
            查看
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['oa:employee-contracts:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['oa:employee-contracts:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <EmployeeContractsForm ref="formRef" @success="getList" />
  <EmployeeContractsDetail ref="viewRef" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter,dateFormatter2, formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import { EmployeeContractsApi, EmployeeContractsVO } from '@/api/oa/employeecontracts'
import EmployeeContractsForm from './EmployeeContractsForm.vue'
import EmployeeContractsDetail from './detail.vue'

/** 员工合同信息 列表 */
defineOptions({ name: 'EmployeeContracts' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EmployeeContractsVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
//记录userId传递过来的值
const props = defineProps({
  userId: {
    type: [Number, String],
    required: false
  }
})
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  contractCategory: undefined,
  contractType: undefined,
  userName: undefined,
  signingCompany: undefined,
  contractName: undefined,
  contractCode: undefined,
  createTime: [],
  userId:  undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 计算合同到期提醒时间 */
const calculateExpiryReminderDays = (effectiveEndDate: any) => {
  if (!effectiveEndDate || effectiveEndDate === '' || effectiveEndDate === null || effectiveEndDate === undefined) {
    return '-'
  }

  try {
    // 处理不同的时间格式
    let endDate: Date
    const endDateValue = effectiveEndDate

    if (typeof endDateValue === 'string') {
      // 如果是字符串格式，直接创建Date对象
      endDate = new Date(endDateValue)
    } else if (typeof endDateValue === 'number') {
      // 如果是数字格式（时间戳），创建Date对象
      endDate = new Date(endDateValue)
    } else {
      // 如果已经是Date对象
      endDate = endDateValue
    }

    // 检查日期是否有效
    if (isNaN(endDate.getTime())) {
      return '-'
    }

    // 获取当前日期（去掉时间部分，只保留日期）
    const currentDate = new Date()
    currentDate.setHours(0, 0, 0, 0)

    // 设置结束日期为当天结束时间
    endDate.setHours(23, 59, 59, 999)

    // 计算天数差
    const diffTime = endDate.getTime() - currentDate.getTime()
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

    // 如果为负数或0，返回 '-'
    if (diffDays <= 0) {
      return '-'
    }

    return `${diffDays} 天`
  } catch (error) {
    console.error('计算合同到期提醒时间时出错:', error)
    return '-'
  }
}

/** 获取到期提醒的样式类 */
const getExpiryReminderClass = (effectiveEndDate: any) => {
  if (!effectiveEndDate || effectiveEndDate === '' || effectiveEndDate === null || effectiveEndDate === undefined) {
    return ''
  }
  
  try {
    // 处理不同的时间格式
    let endDate: Date
    const endDateValue = effectiveEndDate
    
    if (typeof endDateValue === 'string') {
      endDate = new Date(endDateValue)
    } else if (typeof endDateValue === 'number') {
      endDate = new Date(endDateValue)
    } else {
      endDate = endDateValue
    }
    
    // 检查日期是否有效
    if (isNaN(endDate.getTime())) {
      return ''
    }
    
    // 获取当前日期（去掉时间部分，只保留日期）
    const currentDate = new Date()
    currentDate.setHours(0, 0, 0, 0)
    
    // 设置结束日期为当天结束时间
    endDate.setHours(23, 59, 59, 999)
    
    // 计算天数差
    const diffTime = endDate.getTime() - currentDate.getTime()
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    
    // 如果为负数或0（已过期）或小于等于30天（即将到期），返回红色样式
    if (diffDays <= 0 || diffDays <= 30) {
      return 'expiry-warning'
    }
    
    return ''
  } catch (error) {
    console.error('计算到期提醒样式时出错:', error)
    return ''
  }
}

/** 获取到期提醒显示文本 */
const getExpiryDisplayText = (effectiveEndDate: any) => {
  if (!effectiveEndDate || effectiveEndDate === '' || effectiveEndDate === null || effectiveEndDate === undefined) {
    return '-'
  }
  
  try {
    // 处理不同的时间格式
    let endDate: Date
    const endDateValue = effectiveEndDate
    
    if (typeof endDateValue === 'string') {
      endDate = new Date(endDateValue)
    } else if (typeof endDateValue === 'number') {
      endDate = new Date(endDateValue)
    } else {
      endDate = endDateValue
    }
    
    // 检查日期是否有效
    if (isNaN(endDate.getTime())) {
      return '-'
    }
    
    // 获取当前日期（去掉时间部分，只保留日期）
    const currentDate = new Date()
    currentDate.setHours(0, 0, 0, 0)
    
    // 设置结束日期为当天结束时间
    endDate.setHours(23, 59, 59, 999)
    
    // 计算天数差
    const diffTime = endDate.getTime() - currentDate.getTime()
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    
    // 如果为负数或0，返回 '-'
    if (diffDays <= 0) {
      return '-'
    }
    
    return `${diffDays} 天`
  } catch (error) {
    console.error('计算到期提醒显示文本时出错:', error)
    return '-'
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try { 
    const data = await EmployeeContractsApi.getEmployeeContractsPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  props.userId ? formRef.value.open(type, id, props.userId) : formRef.value.open(type, id)
}

/** 查看详情 */
const viewRef = ref()
const openView = (type: string, id: number) => {
  viewRef.value.getInfo(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await EmployeeContractsApi.deleteEmployeeContracts(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await EmployeeContractsApi.exportEmployeeContracts(queryParams)
    download.excel(data, '员工合同信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})

// 监听父组件传入的 userId，变化时更新并重新查询
watch(() => props.userId, (val) => {
  if (val === undefined || val === null || val === '') {
    queryParams.userId = undefined
  } else {
    queryParams.userId = typeof val === 'string' ? Number(val) : val
  }
  queryParams.pageNo = 1
  getList()
})
provide('getList', getList)
</script>

<style scoped>
.expiry-warning {
  color: #f56c6c;
  font-weight: bold;
}
</style>
